﻿@page "/usermapper"
@using System.Net.Http.Headers
@using System.Text.Json
@using Tool.Components.Pages.SmallTools
@using Tool.Models
@using Tool.Services
@using Tool.Utils
@inject ISnackbar snackbar
@inject UserService userService
@inject UidService uidService
@inject IJSRuntime jSRuntime

<PageTitle>UserMapper</PageTitle>
<MudText Typo="Typo.h3" GutterBottom="true">道宫</MudText>

<MudGrid>
    <MudItem xs="12" Class="align-content-center">
        <Login OnSuccess="HandleLogin"></Login>
    </MudItem>
    <MudItem xs="6">
        <MudTextField @bind-Value="_thirdUserId" Label="第三方Id" Variant="Variant.Text" Adornment="Adornment.Start"
                      AdornmentIcon="@Icons.Material.Filled.LockPerson" Clearable="true" />
    </MudItem>
    <MudItem xs="6">
        <MudTextField @bind-Value="_userName" Label="姓名" Variant="Variant.Text" Adornment="Adornment.Start"
                      AdornmentIcon="@Icons.Material.Filled.LockPerson" Clearable="true" />
    </MudItem>

    <MudItem xs="12" Class="align-content-center">
        <Customer SelectedSite="@_selectedSite" ResponseHeaders="@_responseHeaders" OnGetCustomer="HandleCustomer" ButtonText="获取更新脚本"></Customer>
    </MudItem>

    <MudItem xs="4">
        <MudCard>
            <MudCardContent>
                <MudText>管理员用户信息</MudText>
                <MudSimpleTable Dense="true" Hover="true" Style="overflow-x: auto;">
                    <thead>
                        <tr>

                            <th>UserId</th>
                            <th>UserName</th>
                            <th>LoginId</th>

                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var row in _adminUsers)
                        {
                            <tr>

                                <td>@row.Id</td>
                                <td>@row.UserName</td>
                                <td>@row.LoginId</td>

                            </tr>
                        }
                    </tbody>
                </MudSimpleTable>
            </MudCardContent>

        </MudCard>
    </MudItem>
    <MudItem xs="4">
        <MudCard>
            <MudCardContent>
                <MudText>第三方映射用户信息</MudText>
                <MudSimpleTable Dense="true" Hover="true" Style="overflow-x: auto;">
                    <thead>
                        <tr>

                            <th>ArpUserId</th>
                            <th>UserId</th>
                            <th>ArpUserName</th>
                            <th>UserCode</th>

                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var row in _userMappingUsers)
                        {
                            <tr>

                                <td>@row.ArpUserId</td>
                                <td>@row.UserId</td>
                                <td>@row.ArpUserName</td>
                                <td>@row.UserCode</td>
                            </tr>
                        }
                    </tbody>
                </MudSimpleTable>
            </MudCardContent>

        </MudCard>
    </MudItem>
    <MudItem xs="4">
        <MudCard>
            <MudCardContent>
                <MudText>普通用户信息</MudText>
                <MudSimpleTable Dense="true" Hover="true" Style="overflow-x: auto;">
                    <thead>
                        <tr>

                            <th>UserId</th>
                            <th>UserName</th>
                            <th>LoginId</th>

                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var row in _users)
                        {
                            <tr>

                                <td>@row.Id</td>
                                <td>@row.UserName</td>
                                <td>@row.LoginId</td>

                            </tr>
                        }
                    </tbody>
                </MudSimpleTable>
            </MudCardContent>

        </MudCard>
    </MudItem>
    <MudItem xs="6">
        <MudCard>
            <MudCardContent>
                <MudText>管理员匹配结果</MudText>
                @foreach (var result in _adminUserInsertSqls)
                {
                    <div id="adminSql">@result</div>
                }
            </MudCardContent>
            <MudCardActions>
                <MudButton Variant="Variant.Text" Color="Color.Primary" OnClick="ClearData">清除历史</MudButton>
                <MudButton Variant="Variant.Text" Color="Color.Info" OnClick="()=>CopyData(1)">复制</MudButton>
            </MudCardActions>
        </MudCard>
    </MudItem>
    <MudItem xs="6">
        <MudCard>
            <MudCardContent>
                <MudText>用户名匹配结果</MudText>
                @foreach (var result in _userInsertSqls)
                {
                    <div id="userSql">@result</div>
                }
            </MudCardContent>
            <MudCardActions>
                <MudButton Variant="Variant.Text" Color="Color.Primary" OnClick="ClearData">清除历史</MudButton>
                <MudButton Variant="Variant.Text" Color="Color.Info" OnClick="()=>CopyData(2)">复制</MudButton>
            </MudCardActions>
        </MudCard>
    </MudItem>
</MudGrid>
@code
{
    private string _selectedSite = string.Empty;
    private HttpResponseHeaders _responseHeaders;

    private string _thirdUserId { get; set; }
    private string _userName { get; set; }

    private string _userCode;
    private string? _groupName;

    private bool _processing { get; set; }

    private List<UserDto> _adminUsers = new List<UserDto>();
    private List<ArpUserDto> _userMappingUsers = new List<ArpUserDto>();
    private List<UserDto> _users = new List<UserDto>();
    private List<string> _adminUserInsertSqls = new List<string>();
    private List<string> _userInsertSqls = new List<string>();


    private async Task GetSqls()
    {
        _processing = true;
        try
        {
            if (_thirdUserId.IsNullOrEmpty())
            {
                // snackbar.Add("第三方Id不能为空", Severity.Warning);
                return;
            }


            var userTableName = TableHelper.GetTableNameNew("user_base", _userCode, _selectedSite == "sh" ? 1 : 128);

            var adminSql = $"select id, user_name, login_id from {userTableName}  where is_admin=1 and user_code='{_userCode}' and is_delete = 0;"; //获取这个单位的管理员
            _adminUsers = await userService.GetUsers(adminSql, _selectedSite, _responseHeaders, _groupName);
            _users.Clear();
            _userInsertSqls.Clear();
            if (!_userName.IsNullOrEmpty())
            {
                var userSql = $"select id, user_name,login_id from {userTableName} where user_name = '{_userName}' and user_code='{_userCode}' and is_delete = 0;";
                _users = await userService.GetUsers(userSql, _selectedSite, _responseHeaders, _groupName);
            }


            var mappingUsersSql = $"select arp_user_id, arp_user_name,user_id,user_code from user_mapping where arp_user_id = '{_thirdUserId}' and user_code='{_userCode}' and is_delete = 0;"; //获取这个单位的管理员
            _userMappingUsers = await userService.GetArpUsers(mappingUsersSql, _selectedSite, _responseHeaders, _groupName);


            if (_userMappingUsers == null || _userMappingUsers.Count == 0)
            {
                _adminUserInsertSqls.Clear();
                foreach (var item in _adminUsers)
                {
                    _adminUserInsertSqls.Add($"INSERT INTO user_mapping(id, user_id, user_code, arp_user_id, arp_user_name, status, type, is_delete, create_by_id, create_by_name, create_time, update_by_id, update_by_name, update_time, last_update_time) values({await uidService.GetUid()},{item.Id}, '{_userCode}', '{_thirdUserId}', '管理员', 1, 0, 0, NULL, 'liyuan', NOW(), NULL, 'liyuan', NOW(), NOW());");
                }
            }
            else
            {
                _adminUserInsertSqls.Clear();
                if (_userMappingUsers.Count > 1)
                {
                    _adminUserInsertSqls.Add("存在多个映射用户");
                    return;
                }
                if (_adminUsers.Count > 1)
                {
                    _adminUserInsertSqls.Add("存在多个管理");
                    return;
                }
                foreach (var item in _adminUsers)
                {
                    var mappingUser = _userMappingUsers.FirstOrDefault();
                    if (mappingUser == null)
                    {
                        _adminUserInsertSqls.Add($"INSERT INTO user_mapping(id, user_id, user_code, arp_user_id, arp_user_name, status, type, is_delete, create_by_id, create_by_name, create_time, update_by_id, update_by_name, update_time, last_update_time) values({await uidService.GetUid()},{item.Id}, '{_userCode}', '{_thirdUserId}', '管理员', 1, 0, 0, NULL, 'liyuan', NOW(), NULL, 'liyuan', NOW(), NOW());");
                    }
                    else if (mappingUser.UserId != item.Id)
                    {
                        _adminUserInsertSqls.Add($"update user_mapping set user_id={item.Id}, arp_user_name='管理员' where arp_user_id='{mappingUser.ArpUserId}' and user_code='{_userCode}' and is_delete=0;");
                    }
                    else
                    {
                        _adminUserInsertSqls.Add($"用户：{_userName}已经映射成管理员，无需操作");
                    }
                }
            }

            if (_users != null && _users.Count != 0)
            {
                _userInsertSqls.Clear();
                _userInsertSqls.Clear();
                if (_userMappingUsers.Count > 1)
                {
                    _userInsertSqls.Add("存在多个映射用户");
                    return;
                }
                if (_users.Count > 1)
                {
                    _userInsertSqls.Add("存在多个管理");
                    return;
                }

                foreach (var item in _users)
                {
                    var mappingUser = _userMappingUsers.FirstOrDefault();
                    if (mappingUser == null)
                    {
                        _userInsertSqls.Add($"INSERT INTO user_mapping(id, user_id, user_code, arp_user_id, arp_user_name, status, type, is_delete, create_by_id, create_by_name, create_time, update_by_id, update_by_name, update_time, last_update_time) values({await uidService.GetUid()},{item.Id}, '{_userCode}', '{_thirdUserId}', '{item.UserName}', 1, 0, 0, NULL, 'liyuan', NOW(), NULL, 'liyuan', NOW(), NOW());");
                    }
                    else if (mappingUser.UserId != item.Id)
                    {
                        _userInsertSqls.Add($"update user_mapping set user_id={item.Id}, arp_user_name='{_userName}' where arp_user_id='{mappingUser.ArpUserId}' and user_code='{_userCode}'  and is_delete=0;");
                    }
                    else
                    {
                        _userInsertSqls.Add($"用户：{_userName}已经映射成普通用户，无需操作");
                    }
                }
            }

        }
        catch (Exception ex)
        {
            snackbar.Add(ex.Message, Severity.Error);
        }
        finally
        {
            _processing = false;
        }
    }

    private void HandleLogin(LoginResponseDto response)
    {
        _selectedSite = response.SelectedSite;
        _responseHeaders = response.ResponseHeaders;
    }

    private async Task HandleCustomer(CustomerDto customer)
    {
        _groupName = customer.GroupName;
        _userCode = customer.UserCode;
        // _evdNo = $"BX{customer.FinAdmdivCode}{customer.CompanyCode}";
        // await Task.Run(async () => await GetSqls());
        await GetSqls();
    }

    private void ClearData()
    {
        _thirdUserId = string.Empty;
        _userName = string.Empty;
    }

    private async Task CopyData(int type)
    {
        switch (type)
        {
            case 2:
                // await jSRuntime.InvokeVoidAsync("copyToClipboard", string.Join("\n", _userInsertSqls));
                await jSRuntime.InvokeVoidAsync("MyLib.copyToClipboard", string.Join("\n", _userInsertSqls));
				break;
            case 1:
                await jSRuntime.InvokeVoidAsync("MyLib.copyToClipboard", string.Join("\n", _adminUserInsertSqls));
                break;
			default:
                await jSRuntime.InvokeVoidAsync("MyLib.copyToClipboard", string.Join("\n", _adminUserInsertSqls));
				break;
        }
		snackbar.Add("复制成功", Severity.Success);
    }
}